package com.qianfeng.openplateform.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.openplateform.search.bean.ESFieldBean;
import com.qianfeng.openplateform.search.config.EsProperties;
import com.qianfeng.openplateform.search.service.SearchService;
import com.qianfeng.openplateform.search.util.EsUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author 江江
 * @Date 2020/7/30 10:25
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private EsProperties ep;
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean createIndex() {
        try {
            CreateIndexRequest request = new CreateIndexRequest(ep.getIndex());
            request.settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 2).build());
            XContentBuilder builder = EsUtils.getBuilder();
            request.mapping(ep.getType(), builder);
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            return response.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public void saveLogsToEs(ESFieldBean fieldBean) {
        try {
            IndexRequest request = new IndexRequest(ep.getIndex(), ep.getType());
            String jsonBean = objectMapper.writeValueAsString(fieldBean);//对象转换为json
            request.source(jsonBean, XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
